import React,{useState,useEffect} from "react";
import {Text,View,ImageBackground,ScrollView,Pressable,Image,Linking,Alert} from 'react-native';
import Headers from '@/app/components/header/Headers';
import {size,keepTwoDecimalsNoRound} from '@/app/utils';
import { useTranslation } from '@/app/utils/useTranslation';
import {styles} from '@/app/style/home/HomeStyle';
import { Image as ExpoImage } from 'expo-image';
import { useNavigation } from "@react-navigation/native";
import AsyncStorage from '@react-native-async-storage/async-storage';
import {getNoticeList,getListImgs,getJiaoyiDuiApi ,getWalletList} from './home/serve';
interface UserInfo {
    loginName: string | null;
}

interface NoticeItem {
    id?: string;
    title?: string;
    img?: string;
}

interface TabItem {
    id: string;
    name: string;
}

interface TradingPairItem {
    symbolImg?: string;
    coinSymbol?: string;
    baseSymbol?: string;
    openPrice?: string | number;
    transaction24?: string | number;
    price?: string | number;
    priceCny?: string | number;
}

let HomeScreen = (props:any)=>{
  const { t } = useTranslation();
  let navigation = useNavigation<any>();
  let [userInfo,setUserInfo] = useState<UserInfo>({
      loginName:null
  });
  let [noticeList,setNoticeList] = useState<NoticeItem>({title:''});
  let [bannerList,setBannerList] = useState<NoticeItem[]>([{},{},]);
  let [tabIndex,setTabIndex] = useState<number>(0);
  let [totalPrice,settotalPrice] = useState<string | null>(null);
  let [eye,setEye] = useState<boolean>(false);
  let [jiaoyiduilist,setJiaoyiduilist] = useState<TradingPairItem[]>([{},{},{},{},{},{},{},{},{},{},{},{},{}]);
  let [jiaoyiduiloading,setJiaoyiduiloading] = useState<boolean>(true)
  let [tabList,setTabList] = useState<TabItem[]>([
        {
            id:'0',
            name:t('t407')
        },
  ]);
  useEffect(()=>{
    const checkUserInfoStatus = async () => {
      try {
        const value = await AsyncStorage.getItem('userInfo');
        if (value) {
          setUserInfo(JSON.parse(value));
        }
      } catch (e) {
        console.error('获取登录状态时出错', e);
      }
    };
    checkUserInfoStatus();
    getNoticeListInit();
    getNoticeListInit('6');
    getInit();
    getJiaoyiDui();
  },[])

  useEffect(() => {
       
    }, []);

  // 每秒刷新一次交易对列表
  useEffect(()=>{
      const intervalId: any = setInterval(() => {
          getJiaoyiDui();
          getInit();
      }, 2000);
      return () => clearInterval(intervalId);
  },[])

  const getNoticeListInit=(type='')=>{
      let params={
          page:1,
          palimitge:10,
          type:type
      }
      getNoticeList(params).then(res=>{
          let data = res.data||{};
          let list = data.data||[];
          if(list.length>0){
              setNoticeList(list[0]);
          }
          if(type){
              setBannerList(list)
          }
      }).catch(()=>{

      })
  }

  const getInit=()=>{
      getWalletList().then(res=>{
          let data = res.data||{};
          let zongPrice = data.totalPrice||'0.0000';
          settotalPrice(zongPrice);
      })
      getListImgs({}).then(res=>{
          console.log(res)
      })
  }

  const getJiaoyiDui=()=>{
      getJiaoyiDuiApi({}).then(res=>{
          let data = res.data||[];
          setJiaoyiduilist(data);
          setJiaoyiduiloading(false);
      }).catch(err=>{

      })
  }

  function onTabChange(data: string){
      const nextIndex = Number(data);
      if(nextIndex===tabIndex){
          return false;
      }
      setTabIndex(nextIndex);
  }
  return(
      <View style={{ flex: 1,backgroundColor:"#fff"}}>
          <Headers
              border={false}
              barStyle={0}
              setTranslucent={false}
              rightIcon={require('@/assets/images/home/2.png')}
              leftTitle={'返回'}
              backgroundColor={'transparent'}
              centerColor={'#666'}
              {...props}
              leftContent={
                  <Pressable onPress={()=>{
                      navigation.navigate('pages/UserInfoScreen/UserInfoScreen');
                  }} style={styles.touxiangbox}>
                      <ImageBackground style={styles.touxiangimgbox} source={
                          require('@/assets/images/home/1.png')
                      }></ImageBackground>
                  </Pressable>
              }
              centerContent={
                  <View style={{marginLeft:-15}}> 
                      <Text style={styles.navcenterbox} numberOfLines={1}>{userInfo.loginName?userInfo.loginName:''}</Text>
                  </View>
              }
              onClickRightBtn={()=>{
                  console.log('点击了');
              }}
          />
          <ScrollView style={{flex:1,paddingTop:size(10)}}>
              <View>
                  <View style={{alignItems:"center",justifyContent:"center"}}>
                      <View style={styles.infocardbox}>
                          <View style={styles.infocardleftbox}>
                              <View style={styles.infocardleftboxrow}>
                                  <Image
                                      style={styles.infocardleftboximg}
                                      source={
                                          require('@/assets/images/home/5.png')
                                      }
                                  />
                                  <View>
                                      <Text style={styles.infocardleftboxrowtext}>{t('t23')}</Text>
                                  </View>
                                  <Pressable onPress={()=>{
                                      setEye(!eye);
                                  }}>
                                  <Image style={styles.icon} source={eye?require('@/assets/images/eye.png'):require('@/assets/images/noeye.png')} />
                              </Pressable>
                              </View>
                              <View>
                                  <Text style={styles.infocardboxzongjine} numberOfLines={1}>{eye?'$'+keepTwoDecimalsNoRound(totalPrice||0):'********'}</Text>
                              </View>
                              <View>
                                  <Text style={styles.infocardboxzongjinedesc}>MRE  <Text style={styles.infocardboxzongjine2desc}>{eye?keepTwoDecimalsNoRound(totalPrice||0):'********'}</Text></Text>
                              </View>
                          </View>
                          <Image
                              style={styles.infocardimg}
                              source={
                                  require('@/assets/images/home/4.png')
                              }
                          />
                      </View>
                  </View>
                  <View style={styles.menuiconbox}>
                      <Pressable style={styles.menuitemiconbox}  onPress={()=>{
                          props.navigation.navigate('chongZhi', { type: 1})
                      }}>
                          <Image
                              style={styles.menuitemicon}
                              source={
                                  require('@/assets/images/home/6.png')
                              }
                          />
                          <Text numberOfLines={1} style={styles.menuitemicontext}>{t('t24')}</Text>
                      </Pressable>
                      <Pressable style={styles.menuitemiconbox}  onPress={()=>{
                          props.navigation.navigate('jieDian', { type: 1})
                      }}>
                          <Image
                              style={styles.menuitemicon}
                              source={
                                  require('@/assets/images/home/7.png')
                              }
                          />
                          <Text numberOfLines={1} style={styles.menuitemicontext}>{t('t285')}</Text>
                      </Pressable>
                      <View style={styles.menuitemiconbox}>
                          <Image
                              style={styles.menuitemicon}
                              source={
                                  require('@/assets/images/home/8.png')
                              }
                          />
                          <Text numberOfLines={1} style={styles.menuitemicontext}>{t('t408')}</Text>
                      </View>
                      <Pressable onPress={()=>{
                          props.navigation.navigate('mreWike');
                      }} style={styles.menuitemiconbox}>
                          <Image
                              style={styles.menuitemicon}
                              source={
                                  require('@/assets/images/home/9.png')
                              }
                          />
                          <Text numberOfLines={1} style={styles.menuitemicontext}>{t('t409')}</Text>
                      </Pressable>
                  </View>
                  <Pressable onPress={()=>{
                    navigation.navigate('pages/Notice/NoticeScreen')
                  }} style={styles.noticebox}>
                      <Image
                          style={styles.noticeboxleftimg}
                          source={
                              require('@/assets/images/home/10.png')
                          }
                      />
                      <View style={styles.noticetextbox}>
                          <Text style={styles.noticetextboxtext} numberOfLines={1}>{noticeList.title?noticeList.title:""}</Text>
                      </View>
                      <Image
                          style={styles.noticeboxrightimg}
                          source={
                              require('@/assets/images/home/11.png')
                          }
                      />
                  </Pressable>
                  <ScrollView horizontal={true} style={styles.swiperbox} showsHorizontalScrollIndicator={false}>
                      {bannerList.map((item,index)=>{
                          return <Pressable onPress={()=>{
                            navigation.navigate('pages/Notice/NoticeDeatilScreen',{id:item.id,title:item.title})
                          }} style={[styles.swiperitembox,{marginLeft:size(20),width:size(bannerList.length==1?335:320),borderRadius:size(10),overflow:'hidden'}]} key={index}>
                              <ImageBackground style={[styles.swiperitembox,{marginLeft:0,width:size(bannerList.length==1?335:320)}]} source={{uri:item.img}}></ImageBackground>
                          </Pressable>
                      })}
                      {bannerList.length>1?<View style={{width:size(20)}}></View>:null}
                  </ScrollView>
                  <ScrollView horizontal={true} style={styles.tabbox} showsHorizontalScrollIndicator={false}>
                      {tabList.map((item,index)=>{
                          return (<Pressable key={index} onPress={()=>{
                                  onTabChange(item.id);
                                  }} style={[styles.tabItembox,{marginLeft:index==0?size(0):size(10),marginRight:(index==tabList.length-1)?size(10):size(0)}]}>
                                  <Text style={[styles.tabItemtextbox,tabIndex+''==index+''?styles.tabItemActive:null,]}>{t('t407')}</Text>
                              </Pressable>
                          )
                      })}
                  </ScrollView>
                  <View style={{paddingBottom:size(30)}}>
                      <View style={styles.tabletheader}>
                          <View style={styles.tabletheaderleft}>
                              <Text style={styles.nametext}>{t('t306')}</Text>
                          </View>
                          <View style={styles.tabletheadercenter}>
                              <Text style={[styles.tableright,styles.nametext]}>{t('t307')}</Text>
                          </View>
                          <View style={styles.tabletheaderright}>
                              <Text style={[styles.tableright,styles.nametext]}>{t('t308')}</Text>
                          </View>
                      </View>
                      {jiaoyiduilist.map((item,index)=>{
                          if(jiaoyiduiloading){
                              return (
                                  <View key={index} style={[styles.tabletheader,styles.listItem]}>
                                      <View style={[styles.tabletheaderleft]}>
                                      <View style={styles.tabletheaderlefticon}>
                                              
                                      </View>
                                      <View style={styles.tabletheaderlefttextgroup}>
                                          <View style={{height:size(20),backgroundColor:'#f9f9f9',width:size(60)}}></View>
                                          <View style={{height:size(16),backgroundColor:'#f9f9f9',width:size(60),marginTop:size(4)}}></View>
                                      </View>
                                      </View>
                                      <View style={[styles.tabletheadercenter,{alignItems:'flex-end'}]}>
                                          <View style={{height:size(20),backgroundColor:'#f9f9f9',width:size(60)}}></View>
                                          <View style={{height:size(16),backgroundColor:'#f9f9f9',width:size(60),marginTop:size(4)}}></View>
                                      </View>
                                      <View style={styles.tabletheaderright}>
                                          <View style={{width:size(71),height:size(31),backgroundColor:'#f9f9f9'}}>
                                              {/* <Text numberOfLines={1} style={[styles.tableright,styles.nametext,styles.tabletheaderrightbtntext]}>-3.43%</Text> */}
                                          </View>
                                      </View>
                                  </View>
                              )
                          }else{
                              return (
                                  <Pressable key={index} style={[styles.tabletheader,styles.listItem]} onPress={()=>{
                                      props.navigation.navigate('tongJiTu',item);
                                  }}>
                                      <View style={[styles.tabletheaderleft]}>
                                      <View style={styles.tabletheaderlefticon}>
                                        <ExpoImage
                                          source={{ uri: item.symbolImg?item.symbolImg:''}}
                                          contentFit="cover"
                                          transition={200}
                                          style={styles.tabletheaderlefticon}
                                        />
                                      </View>
                                      <View style={styles.tabletheaderlefttextgroup}>
                                              <Text numberOfLines={1} style={styles.listItemName}>{item.coinSymbol?item.coinSymbol:''}<Text style={styles.listItemName2}>/{item.baseSymbol?item.baseSymbol:''}</Text></Text>
                                              <Text numberOfLines={1} style={styles.listItemdesc}>{t('t309')} <Text>{item.transaction24?keepTwoDecimalsNoRound(item.transaction24):'0.00'}</Text></Text>
                                      </View>
                                      </View>
                                      <View style={styles.tabletheadercenter}>
                                          <Text numberOfLines={1} style={[styles.tableright,styles.nametext,styles.listItemjiage]}>{item.price?keepTwoDecimalsNoRound(item.price):'0.00'}</Text>
                                          <Text numberOfLines={1} style={[styles.tableright,styles.nametext,styles.listItemrmbjiage]}>≈￥{item.priceCny?keepTwoDecimalsNoRound(item.priceCny):'0.00'}</Text>
                                      </View>
                                      <View style={styles.tabletheaderright}>
                                          <View style={[styles.tabletheaderrightbtn,{backgroundColor:Number(item.openPrice)<0?'#EB4B6D':'#13C57E'}]}>
                                              <Text numberOfLines={1} style={[styles.tableright,styles.nametext,styles.tabletheaderrightbtntext]}>
                                                  {item.openPrice?keepTwoDecimalsNoRound(Number(item.openPrice)*100):"0"}%
                                              </Text>
                                          </View>
                                      </View>
                                  </Pressable>
                              )
                          }
                      })}
                      
                  </View>
              </View>
          </ScrollView>
      </View>
  )
};

export default HomeScreen;